import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.menus && store.getters.menus.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // 这个地方我需要重写并渲染路由
          const { menus } = await store.dispatch('user/getInfo')
          const routes = await store.dispatch('permission/formatMenus', menus)

          router.addRoutes(routes)
          next({ ...to, replace: true })
        } catch (error) {
          Message.error(error || 'Has Error')
          // 把 token 清理掉，如果不清除会出现跳转死循环
          await store.dispatch('user/logout')
          next(`/login`)// ?redirect=${to.path}
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`) //?redirect=${to.path}
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
